/**
 * ActionDispatcherServlet.java
 *
 * Copyright (C) 2009,  Tomislav Milkovic
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package ws4is.servlets.engine;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

/**
 * Generic servlet for dynamic request processing. Servlet parse url parameter
 * "action" which contains class name instance of AbstractAction class.
 */
public abstract class AbstractActionDispatcherServlet extends HttpServlet implements Servlet, IDispatcher {

	private static final long serialVersionUID = 1L;
	private transient String param_action = null;
	private Type mapType = null;
	private Map<String, ConfigObject> services = null;

	public AbstractActionDispatcherServlet() {
		super();
		mapType = new TypeToken<Map<String, ConfigObject>>() {}.getType();
		services = new HashMap<String, ConfigObject>();
	}

	public void init(ServletConfig conf) throws ServletException {
		super.init(conf);
		try {
			load(this.getClass());
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServletException(e);
		}
	}

	// load file from META-INF/actions/ named as abstract class/interface
	// canonical name
	// each line should contain canonical class names implementing
	// interface or abstract class
	private final void load(Class<? extends AbstractActionDispatcherServlet> ifc) throws Exception {
		String vpath = "META-INF/actions/" + ifc.getName() + ".json";

		String s = this.getServletContext().getRealPath(vpath);
		ResourceFinder re = new ResourceFinder(s);

		InputStream is = re.getInputStream();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			StringBuffer sb = new StringBuffer();
			String eachLine = br.readLine();

			while (eachLine != null) {
				sb.append(eachLine);
				eachLine = br.readLine();
			}

			Gson gs = new Gson();
			services = gs.fromJson(sb.toString(), mapType);
			gs = null;
			getClasses();

		}catch(Exception e){
			//TODO log error reading web.xml configuration
			throw e;
		} finally {
			is.close();
		}
	}

	private final void getClasses() {

		Set<Entry<String, ConfigObject>> set = services.entrySet();
		for(Entry<String, ConfigObject> e : set){
			e.getValue().setActionClass();
		}

	}

	// from URL request parameter [action] retrieves action class name,
	// instantiate it and execute method from parameter [cmd]
	// Example :
	// http://localhost:8080/myapp/myservlet/action=EditorAction&cmd=loadLanguages
	// will instantiate EditorAction class (subclass of AbstractAction) and call
	// loadLanguages method
	// loadLanguages method must have HttpServletRequest and HttpServletResponse
	// as input parameters
	protected final void processAction(HTTPRequestType type,	HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		param_action = this.preAction(type, request);

		String actionClass = null;
		if (type == HTTPRequestType.GET) {
			actionClass = request.getParameter(param_action);
		} else {
			
			if (ServletFileUpload.isMultipartContent(request)) {
				
				Cookie[] cookies = request.getCookies();
				for (Cookie cookie : cookies){
					if(param_action.equals(cookie.getName()))
						actionClass =  cookie.getValue();	
				}
								
				type = HTTPRequestType.MULTIPART;
				
			} else {
				Map pmap = request.getParameterMap();
				if (pmap.containsKey(param_action)) {
					actionClass = request.getParameter(param_action);
				}
			}
		}

		if (actionClass == null) {
			printMessage(response ,this.getClass().getSimpleName().concat(" has no regular parameter {action}!!!"));
			return;
		}

		Exception ex = null;
		try {
			ConfigObject co = services.get(actionClass);		
			Constructor<AbstractAction> con = co.getActionConstructor();
			AbstractAction aa = con.newInstance();
			aa.execute(co, type, request, response);
			aa = null;			
		} catch (Exception e) {
			ex = e;
			//TODO log error executing action
			printMessage(response ,e.getMessage());
		} finally {
			this.postAction(type, actionClass, ex);
		}
	}

	/*
	 * Prints error message in jSON format
	 */	
	protected final void printMessage(HttpServletResponse response, String msg) throws UnsupportedEncodingException, IOException{
		PrintWriter pw = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
		JsonObject jobj = new JsonObject();
		jobj.addProperty("success", new Boolean(false));
		jobj.addProperty("msg", msg);	
		Gson gs = new Gson();
		pw.write(gs.toJson(jobj));
		pw.flush();
		pw.close();
		jobj=null;
		gs=null;
	}
	
	protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processAction(HTTPRequestType.GET, request, response);
	}

	protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processAction(HTTPRequestType.POST,request, response);
	}

	protected final void doDelete(HttpServletRequest request,	HttpServletResponse response) throws ServletException, IOException {
		processAction(HTTPRequestType.DELETE, request, response);
	}

	protected final void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processAction(HTTPRequestType.PUT, request, response);
	}

	// protected void doTrace(HttpServletRequest request, HttpServletResponse
	// response)throws ServletException, IOException {
	// processAction(RequestType.TRACE,request, response);
	// }

	// protected void doOptions(HttpServletRequest request, HttpServletResponse
	// response) throws ServletException, IOException {
	// processAction(RequestType.OPTIONS,request, response);
	// }

	// protected void doHead(HttpServletRequest request, HttpServletResponse
	// response) throws ServletException, IOException {
	// processAction(RequestType.HEAD,request, response);
	// }

	// protected void service(HttpServletRequest request, HttpServletResponse
	// response) throws ServletException, IOException {
	// processAction(RequestType.SERVICE,request, response);
	// }

}
